package com.qf.commerce.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.commerce.common.dto.BalanceTransactionsDto;
import com.qf.commerce.entity.BalanceTransactions;
import com.qf.commerce.exception.DaoException;
import com.qf.commerce.mapper.BalanceTransactionsMapper;
import com.qf.commerce.mapper.UserMapper;
import com.qf.commerce.resp.ResponseStatus;
import com.qf.commerce.service.BalanceTransactionsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/*
 * @author 358
 * @since JDK 1.8
 * @data 2023/9/12 19:42
 */

@Service
public class BalanceTransactionsServiceImpl implements BalanceTransactionsService {

    @Resource
    private BalanceTransactionsMapper balanceTransactionsMapper;
    @Resource
    private UserMapper userMapper;


    @Override
    public int updateByPrimaryKeySelective(BalanceTransactions record) {
        return balanceTransactionsMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(BalanceTransactions record) {
        return balanceTransactionsMapper.updateByPrimaryKey(record);
    }

    @Override
    @Transactional
    public BigDecimal add(Integer userId, BigDecimal money, String comment) {
        BigDecimal oldMoney = userMapper.selectByPrimaryKey(userId).getBalance();
        BigDecimal newMoney = oldMoney.add(money);
        int num = userMapper.updateBalanceById(userId,newMoney);
        BalanceTransactionsDto bt = new BalanceTransactionsDto(userId, money, newMoney, 1, comment);
        num += balanceTransactionsMapper.insert(bt);
        if (num > 1) {
            return newMoney;
        } else {
            throw new DaoException(ResponseStatus.GET_DATA_ERROR);
        }
    }

    @Override
    @Transactional
    public BigDecimal subtract(Integer userId, BigDecimal money, String comment) {
        BigDecimal oldMoney = userMapper.selectByPrimaryKey(userId).getBalance();
        BigDecimal newMoney = oldMoney.subtract(money);
        int num = userMapper.updateBalanceById(userId,newMoney);
        BalanceTransactionsDto bt = new BalanceTransactionsDto(userId, money, newMoney, 0, comment);
        num += balanceTransactionsMapper.insert(bt);
        if (num > 0) {
            return newMoney;
        } else {
            throw new DaoException(ResponseStatus.GET_DATA_ERROR);
        }
    }

    @Override
    public PageInfo<BalanceTransactions> listById(Integer userId,Integer page, Integer size) {
        return PageHelper.startPage(page, size).doSelectPageInfo(() -> balanceTransactionsMapper.selectByUserId(userId));
    }
}
